package com.cws.job;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import java.util.Date;
import java.util.List;

import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cws.enmu.JobType;
import com.cws.enmu.Status;
import com.cws.frame.AppInit;
import com.cws.model.SysJob;
import com.cws.sys.Mem;

public class JobMonitor implements Job {

	Logger log = LoggerFactory.getLogger(JobMonitor.class);

	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {

		try {

			//log.debug("TaskMonitor run start.");

			List<SysJob> taskList = SysJob.dao.getAll();

			for (SysJob job : taskList) {

				String jobId = job.getStr("id");

				if (job.get("isEnable").equals(Status.TRUE.name())) {

					if (!Mem.getValidTaskInfo().contains(jobId)) {

						//将任务添加到任务调度器
						changeTaskStatus(job, Status.TRUE);
						//任务添加到内存有效任务
						Mem.addValidTask(jobId);
						log.info("TaskMonitor start task[" + jobId + "] success.");
					}
				} else {
					if (Mem.getValidTaskInfo().contains(jobId)) {

						//将任务从任务调度器中移除
						changeTaskStatus(job, Status.FALSE);
						//从内存有效任务中移除
						Mem.removeValidTask(jobId);
						log.info("TaskMonitor stop task[" + jobId + "] success.");
					}
				}
			}

			//log.debug("TaskMonitor run end.");

		} catch (Exception e) {
			log.error("TaskMonitor exec error.", e);
		}

	}

	/**
	 * 更新任务调度规则及状态
	 * @param task
	 * @param status
	 * @throws Exception 
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void changeTaskStatus(SysJob job, Status status) throws Exception {

		//获取调度信息
		String jobId = job.getStr("id");
		String jobType = job.getStr("jobType");

		String jobClassName = JobType.valueOf(jobType).getJobClass();
		String jobCronExp = job.getStr("cronExp");

		Class clazz = Class.forName(jobClassName);
		JobDetail jobDetail = newJob(clazz).withIdentity(jobId, jobType).build();

		CronTrigger trigger = newTrigger().withIdentity(jobId, jobType).withSchedule(cronSchedule(jobCronExp)).build();

		jobDetail.getJobDataMap().put("jobObj", job);
		
		if (Boolean.valueOf(status.name())) {
			Date ft = AppInit.getSchedulerFactory().getScheduler().scheduleJob(jobDetail, trigger);
			log.info("TaskMonitor add task[" + jobId + "]" + "run at: " + ft + " and repeat based on expression: "
					+ trigger.getCronExpression());

	
		} else {

			AppInit.getSchedulerFactory().getScheduler().deleteJob(jobDetail.getKey());

			log.info("TaskMonitor delete task[" + jobId + "] success");
		}

	}
}
